﻿using Agriculture.Api.Read.AllError;
using Agriculture.Api.Read.Application.Command;
using Agriculture.Api.Read.Application.Handler;
using Agriculture.Api.Read.Common;
using Agriculture.Api.Read.Files;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NLog.Web;
using System.Reflection;
using System.Text;

namespace Agriculture.Api.Read.Extensions
{
    /// <summary>
    /// 扩展方法 静态类 静态方法 this关键字
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {
            // Add services to the container.
            //注册全局异常处理
            builder.Services.AddControllers(x => x.Filters.Add<GloabIExcptionfilter>());

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //中文注释
            builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "Agriculture.Api.Read.xml", true));
            
            //移除EF Core DbContext注册，因为我们使用Dapper直接执行SQL查询
            
            //JWT
            var jwtSettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
            //授权认证（使用JWT）
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SigningKey);
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = jwtSettings.Issuer,

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = jwtSettings.Audience,

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });

            // 添加授权服务
            builder.Services.AddAuthorization();

            // 配置Swagger
            builder.Services.AddSwaggerGen(o =>
            {
                // 显示 授权信息
                o.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[]
                        {

                        }
                    }
                });
            });
            //注册consul
            //builder.Configuration.Register();
            //注册中介者
            builder.Services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            
            // 注册退款申请查询处理器
            builder.Services.AddTransient<IRequestHandler<RefundApplicationQuery, RefundApplicationQueryResult>, RefundApplicationQueryHandler>();
            builder.Services.AddTransient<IRequestHandler<RefundApplicationDetailQuery, RefundApplicationDetailResult>, RefundApplicationDetailQueryHandler>();
            
            // 注册药品订单查询处理器
            builder.Services.AddTransient<IRequestHandler<MedicineOrderQuery, MedicineOrderQueryResult>, MedicineOrderQueryHandler>();
            builder.Services.AddTransient<IRequestHandler<MedicineOrderDetailQuery, MedicineOrderDetailResult>, MedicineOrderDetailQueryHandler>();
            builder.Services.AddTransient<IRequestHandler<LogisticsTrackingQuery, LogisticsTrackingResult>, LogisticsTrackingQueryHandler>();
            
            // 注册处方流转订单查询处理器
            builder.Services.AddTransient<IRequestHandler<PrescriptionOrderQuery, PrescriptionOrderQueryResult>, PrescriptionOrderQueryHandler>();
            builder.Services.AddTransient<IRequestHandler<PrescriptionOrderDetailQuery, PrescriptionOrderDetailResult>, PrescriptionOrderDetailQueryHandler>();
            
            // 注册问诊单查询处理器
            builder.Services.AddTransient<IRequestHandler<ConsultationOrderQuery, ConsultationOrderQueryResult>, ConsultationOrderQueryHandler>();
            builder.Services.AddTransient<IRequestHandler<ConsultationOrderDetailQuery, ConsultationOrderDetailResult>, ConsultationOrderDetailQueryHandler>();
            
            // 注册挂号订单查询处理器
            builder.Services.AddTransient<IRequestHandler<RegistrationOrderQuery, RegistrationOrderQueryResult>, RegistrationOrderQueryHandler>();
            builder.Services.AddTransient<IRequestHandler<RegistrationOrderDetailQuery, RegistrationOrderDetailResult>, RegistrationOrderDetailQueryHandler>();
            
            // 注册用户登录服务
            builder.Services.AddTransient<IRequestHandler<UserLoginCommand, UserLoginResult>, UserLoginCommandHandler>();
            
            //配置AutoMapper
            builder.Services.AddAutoMapper(typeof(MapperProfiles));
            //配置日志
            builder.Host.UseNLog();

            return builder;
        }
    }
}
